import type { IObject } from './interface';

/**
 * 获取路由参数
 * @returns
 */
const getUrlParams = (): IObject => {
  const url = window.location.href;
  const params: IObject = {};
  let strArr: string[] = [];
  try {
    if (url) {
      const strArr1: string[] = url.split('?');
      if (strArr1.length === 3) {
        const corpid: string = strArr1[1].split('#')[0].split('=')[1];
        params.corpid = corpid;
        strArr = strArr1[2].split('&');
      } else {
        const str1: string = url.split('?')[1].split('#')[0];
        strArr = str1.split('&');
      }
      strArr.forEach((item: string) => {
        const [key, value] = item.split('=');
        params[key] = value;
      });
    }
    return params;
  } catch {
    return {};
  }
};

/**
 * 递归查询数据
 * @param data 数据源
 * @param value 目标数据
 * @param key 对象中健的值
 * @returns
 */
const accordingKeyReturnResult = (data: any[], value: any, key: string): any | null => {
  if (!data || !data.length) {
    return null;
  }
  for (const node of data) {
    if (node[key] === value) {
      return node;
    }
    const find = accordingKeyReturnResult(node.children, value, key);
    if (find) {
      return find;
    }
  }
  return null;
};

export { getUrlParams, accordingKeyReturnResult };
